<template>
    <!--弹出窗-->
    <modal ref="modal_1"
           :title="title"
           :isCloseConfirm="this.editable"
           :fullscreen="this.fullscreen"
           top="3%"
           width="80%"
           :close-on-click-modal="true"
           @modalOpened="opened"
           @modalClose="closed">

        <avue-form :option="option"
                   ref="form"
                   v-model="form"
                   @submit="onSubmit">

            <template #stockTransferItem>
                <stock-transfer-item ref="stockTransferItem" :transferOutId="this.form.transferOutId" :transferInId="this.form.transferInId" @disabledFiled="disabledFiled">

                </stock-transfer-item>
            </template>
        </avue-form>
        <!--底部按钮块, 默认只有"取消"按钮-->
        <template #footerButton>
            <el-button
                    type="primary"
                    v-if="(permission.stock_transfer_add || permission.stock_transfer_edit) && editable"
                    :loading="btnLoading"
                    @click="this.$refs.form.submit()"
            >保 存
            </el-button>
            <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
        </template>
    </modal>
</template>

<script>
    import {add, getDetail,saveStockTransfer} from "@/api/anwise/stock/stock_transfer";
    import {stockHomeSelect} from "@/api/anwise/stock_home";
    import {userCompany} from "@/api/anwise/common";
    import {mapGetters} from "vuex";
    import {dateFormat} from "@/utils/date.js";
    import stockTransferItem from './stock_transfer_item.vue';

    export default {
        components: {
            stockTransferItem,
        },
        data() {
            return {
                emits: ["success"],
                dept:'',
                editable: false,
                title: "调拨单信息",
                isCloseConfirm: false,
                fullscreen: false,
                form: {},
                query: {},
                loading: true,
                btnLoading: false,
                supType:"",
                toNoPlaceholder:"",
                toNamePlaceholder:"",
                isRole:"",
                supplierData:{},
                anwiseData:{},
                stockHomeDic:[],
                hasItem:false,
                option: {
                    card: true,
                    tabs: true,
                    tabsActive: 1,
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "调拨单号",
                            prop: "idNo",
                            type: "input",
                            span:8,
                            placeholder:'保存后自动生成单号',
                            disabled:true,
                        },
                        {
                            label: "所属机构",
                            prop: "deptName",
                            type: "input",
                            disabled:true,
                            span:8,
                            overHidden: true,
                            sortable: true,
                        },
                        {
                            label: "调拨日期",
                            prop: "transferDate",
                            type: "date",
                            span:8,
                            overHidden: true,
                            sortable: true,
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                        },
                        {
                            label: "调出仓库名称",
                            prop: "transferOutId",
                            type:"select",
                            filterable: true,
                            span:8,
                            dicData:[],
                            props: {
                                label: 'stockName',
                                value: 'id',
                            },
                            change:	({column,value})=>{this.changeTransferOut(column,value);},
                            blur:({column,value})=>{this.blurTransferOut(column,value);},
                            dataType: 'string',
                            rules: [{
                                required: true,
                                message: "请选择调出仓库",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "调入仓库名称",
                            prop: "transferInId",
                            type:"select",
                            filterable: true,
                            span:8,
                            dicData:[],
                            props: {
                                label: 'stockName',
                                value: 'id',
                            },
                            change:	({column,value})=>{this.changeTransferIn(column,value);},
                            blur:({column,value})=>{this.blurTransferIn(column,value);},
                            dataType: 'string',
                            rules: [{
                                required: true,
                                message: "请选择调入仓库",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "调拨备注",
                            prop: "remark",
                            type: "textarea",
                            maxlength: 2000,
                            minRows:2,
                            span: 24,
                        },
                        {
                            label: "操作日期",
                            prop: "createTime",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span: 12,
                            disabled:true,
                            overHidden: true,
                            sortable: true,
                        },
                        {
                            label: "生成出仓单号",
                            prop: "stockOutNo",
                            type: "input",
                            span: 12,
                            disabled:true,
                            overHidden: true,
                            sortable: true,
                        },
                        {
                            label: "操作人员",
                            prop: "createUserName",
                            type: "input",
                            span: 12,
                            disabled:true,
                            overHidden: true,
                            sortable: true,
                        },

                        {
                            label: "生成入仓单号",
                            prop: "stockInNo",
                            type: "input",
                            span: 12,
                            disabled:true,
                            overHidden: true,
                            sortable: true,
                        },
                    ],
                    group: [
                        {
                            icon: 'el-icon-house',
                            label: '调拨项信息',
                            prop: 'group1',
                            column: [
                                {
                                    label: '',
                                    prop: 'stockTransferItem',
                                    className: 'addPadding',
                                    span: 24,
                                    labelWidth: 0,
                                    formslot: true,
                                    display: true,
                                },
                            ],
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission","userInfo"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.stock_transfer_add, false),
                    viewBtn: this.validData(this.permission.stock_transfer_view, false),
                    delBtn: this.validData(this.permission.stock_transfer_delete, false),
                    editBtn: this.validData(this.permission.stock_transfer_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            },
            isAnwiseProdRole(){//安伟生产角色
                return this.userInfo.role_id.includes("1717966761333272578");
            },
            isJiagongshangRole(){//加工商角色
                return this.userInfo.role_id.includes("1717966543397236738");
            },
            isPurchaseRole(){//采购商角色
                return this.userInfo.role_id.includes("1728951498503839746");
            },
            isAnwiseDept(){
                return '1683670943851282433';
            },
        },
        mounted() {
            this.init();
        },
        methods: {
            disabledFiled(hasItem) {
                this.hasItem = hasItem;
                const transferOutId = this.findObject(this.option.column, 'transferOutId');
                transferOutId.disabled = hasItem;
                const transferInId = this.findObject(this.option.column, 'transferInId');
                transferInId.disabled = hasItem;
            },
            init() {
                userCompany().then(res=>{
                    if (res.data.success) {
                        this.dept = res.data.data;
                        if (!this.dept) {
                            this.$message({
                                type: "error",
                                message: "用户无组织机构信息，请联系安伟工作人员！"
                            });
                            return;
                        } else {
                            this.isRole = this.dept.bodyType;
                        }
                    }
                })
            },
            changeTransferIn(column,value){
               this.stockHomeDic.forEach(item=>{
                   if(item.id === value){
                       this.form.transferInName = item.stockName;
                   }
               })
            },
            blurTransferIn(column,value){
                if(value === this.form.transferOutId && value){
                    this.form.transferInId = "";
                    value = "";
                    this.$message({
                        type: 'error',
                        message: '调出仓库与调入从仓库不能相同！',
                    });
                    return;
                }
            },
            changeTransferOut(column,value){
                this.stockHomeDic.forEach(item=>{
                    if(item.id === value){
                        this.form.transferOutName = item.stockName;
                    }
                })
            },
            blurTransferOut(column,value){
                if(value === this.form.transferInId && value){
                    this.form.transferOutId = "";
                    value = "";
                    this.$message({
                        type: 'error',
                        message: '调出仓库与调入从仓库不能相同！',
                    });
                    return;
                }
            },
            async validItemEvent() {
                const $table = this.$refs.stockTransferItem.$refs.tableRef
                let errMap = undefined;
                await $table.fullValidate().then((err) => {
                    errMap=err;
                    console.log("err",err)
                })
                return errMap;
            },
            async onSubmit(form, done) {
                const $table = this.$refs.stockTransferItem.$refs.tableRef
                let checkItem = false;
                const errMap = await this.validItemEvent();

                if (errMap) {
                    this.$message({
                        type: 'error',
                        message: '调拨项信息有误！',
                    });
                    checkItem = true;
                    done();
                    return;
                }
                if (!checkItem) {
                    this.btnLoading = true;
                    form.addList = $table.getInsertRecords();
                    form.updateList = $table.getUpdateRecords();
                    form.deleteList = $table.getRemoveRecords();
                    const itemList = $table.getTableData().fullData;
                    if (!itemList || itemList.length < 1) {
                        this.$message({
                            type: 'error',
                            message: '无出仓项信息！',
                        });
                        this.btnLoading = false;
                        done();
                        return;
                    }
                    saveStockTransfer(form).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: res.msg || "保存成功!"
                            });
                            setTimeout(() => {
                                this.btnLoading = false;
                                done();
                                this.$refs.modal_1.hide();
                            }, 1000)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg || "保存失败!"
                            });
                        }
                    }).catch(err => {
                        console.log(err)
                        done();
                        this.btnLoading = false;
                    })

                }
            },
            show(option) {
                stockHomeSelect().then(res=>{
                    if(res.data.success){
                        const transferOut = this.findObject(this.option.column, 'transferOutId');
                        const transferIn = this.findObject(this.option.column, 'transferInId');
                        this.stockHomeDic = res.data.data;
                        transferOut.dicData = this.stockHomeDic;
                        transferIn.dicData = this.stockHomeDic;
                    }
                })
                if (option.id) {
                    setTimeout(() => {
                        getDetail(option.id).then(res =>{
                            if (res.data.success) {
                                this.form = res.data.data;
                                this.$refs.stockTransferItem.setData(this.editable, this.form.idNo)
                                console.log(this.form)
                            }
                        })
                    }, 500);
                } else {
                    this.form={}
                    this.hasItem=false;
                    this.form.transferDate = dateFormat(new Date(),"yyyy-MM-dd");
                }
                this.form.deptName = this.dept.deptName;
                this.form.deptId = this.dept.id;
                this.title = option.title;
                this.type = option.type;
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                this.$refs.modal_1.show();
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage){
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            },
            opened() {
                console.log("opened")
            },
            closed() {
                this.$emit("success");
            }
        }
    };
</script>

<style>
</style>
